<?php
class loader
{
	private $controllerName;
	private $actionName;
	private $login;
	private $controller;
	private $request;
	
	public function __construct()
	{
		$this->login = new LoginController('Login');
	}
	
	public function GetRequest()
	{
		return $this->request;
	}
	
	private function FillRequest()
	{
		foreach ($_POST as $key => $value)
		{
			$this->request[$key] = $value;
		}
		foreach ($_GET as $key => $value)
		{
			$this->request[$key] = $value;
		}
	}
	
	public function GetController()
	{
		return $this->controller;
	}
	
	public function GetAction()
	{
		return $this->action;
	}
	
	private function ParseUrl()
	{
		$url = $_SERVER['REQUEST_URI'];
		$arguments = explode('/', $url);

		foreach($arguments as $key=>$arg)
		{
			if ($arg == '')
				unset($arguments[$key]);
		}
		
		$this->controllerName = !isset($arguments[1]) ? DEFAULT_CONTROLLER : $arguments[1];
		$this->actionName = !isset($arguments[2]) ? DEFAULT_ACTION : $arguments[2];
		$i = 3;
		while($i < count($arguments))
		{
			$this->request[$arguments[$i]] = $arguments[$i+1];
			$i = $i+2;
		}
	}
	
	public function PageLoad()
	{
		$this->ParseUrl();
		$this->FillRequest();
		
		if ($this->controllerName == 'Content')
			return;
		
		ob_start();
		if (!$this->login->ActionLogin($this->request))
		{
			$db = new DbContext();
			$connec = $db->getConnection();

			$query = "INSERT INTO visit (ip_adress, date) VALUES (?, NOW())";

			$q=$connec->prepare($query); 
			$q->execute(array($_SERVER["REMOTE_ADDR"])) or die(print_r($q->errorInfo(), true));
			
			$this->controller = $this->login;
			$this->controller->data['title'] = 'Connexion';
			$this->login->View('Login.php');
		}
		else
		{
			$controllerName = $this->controllerName.'Controller';
			$actionName = 'Action'.$this->actionName;
			$this->controller = new $controllerName($this->actionName);		
			$this->controller->$actionName($this->request);
		}
	}
}
?>
